<?php
require_once '../config.php';
require_once 'BaseAPI.php';

handleCORS();

class AuthAPI extends BaseAPI {
    
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        
        // 优先从GET/POST参数获取action，兼容虚拟主机
        $action = $_GET['action'] ?? $_POST['action'] ?? '';
        
        // 如果没有action参数，尝试从URL路径解析
        if (empty($action)) {
            $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
            $pathParts = explode('/', trim($path, '/'));
            $action = end($pathParts);
            
            // 移除.php后缀
            $action = str_replace('.php', '', $action);
        }
        
        try {
            switch ($method) {
                case 'POST':
                    switch ($action) {
                        case 'register':
                            $this->register();
                            break;
                        case 'login':
                            $this->login();
                            break;
                        case 'logout':
                            $this->logout();
                            break;
                        case 'refresh':
                            $this->refreshToken();
                            break;
                        default:
                            sendErrorResponse('未找到对应的API接口', 404);
                    }
                    break;
                case 'GET':
                    switch ($action) {
                        case 'profile':
                            $this->getProfile();
                            break;
                        case 'verify':
                            $this->verifyToken();
                            break;
                        default:
                            sendErrorResponse('未找到对应的API接口', 404);
                    }
                    break;
                case 'PUT':
                    switch ($action) {
                        case 'profile':
                            $this->updateProfile();
                            break;
                        case 'password':
                            $this->changePassword();
                            break;
                        default:
                            sendErrorResponse('未找到对应的API接口', 404);
                    }
                    break;
                default:
                    sendErrorResponse('不支持的请求方法', 405);
            }
        } catch (Exception $e) {
            logActivity("API错误: " . $e->getMessage(), 'ERROR');
            sendErrorResponse('服务器内部错误', 500);
        }
    }
    
    private function register() {
        $data = getRequestData();
        
        // 验证输入
        $rules = [
            'username' => [
                'required' => true,
                'min_length' => 3,
                'max_length' => 50,
                'pattern' => '/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]+$/u',
                'message' => '用户名只能包含字母、数字、下划线和中文，长度3-50个字符'
            ],
            'email' => [
                'required' => true,
                'email' => true,
                'max_length' => 100,
                'message' => '请输入有效的邮箱地址'
            ],
            'password' => [
                'required' => true,
                'min_length' => PASSWORD_MIN_LENGTH,
                'message' => '密码长度不能少于' . PASSWORD_MIN_LENGTH . '个字符'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $username = $data['username'];
        $email = $data['email'];
        $password = $data['password'];
        
        // 检查用户名和邮箱是否已存在
        $stmt = $this->db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        
        if ($stmt->fetch()) {
            sendErrorResponse('用户名或邮箱已存在');
        }
        
        // 创建用户
        $passwordHash = hashPassword($password);
        $stmt = $this->db->prepare("
            INSERT INTO users (username, email, password_hash) 
            VALUES (?, ?, ?)
        ");
        
        if ($stmt->execute([$username, $email, $passwordHash])) {
            $userId = $this->db->lastInsertId();
            
            // 创建会话
            $sessionData = $this->createSession($userId);
            
            logActivity("用户注册成功: $username");
            sendSuccessResponse([
                'user' => [
                    'id' => $userId,
                    'username' => $username,
                    'email' => $email
                ],
                'session' => $sessionData
            ], '注册成功');
        } else {
            sendErrorResponse('注册失败，请稍后重试');
        }
    }
    
    private function login() {
        $data = getRequestData();
        
        // 验证输入
        $rules = [
            'login' => ['required' => true, 'message' => '请输入用户名或邮箱'],
            'password' => ['required' => true, 'message' => '请输入密码']
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $login = $data['login'];
        $password = $data['password'];
        $rememberMe = isset($data['remember_me']) ? (bool)$data['remember_me'] : false;
        
        // 查找用户
        $stmt = $this->db->prepare("
            SELECT id, username, email, password_hash, status 
            FROM users 
            WHERE username = ? OR email = ?
        ");
        $stmt->execute([$login, $login]);
        $user = $stmt->fetch();
        
        if (!$user || !verifyPassword($password, $user['password_hash'])) {
            logActivity("登录失败: $login", 'WARNING');
            sendErrorResponse('用户名/邮箱或密码错误');
        }
        
        if ($user['status'] !== 'active') {
            sendErrorResponse('账户已被禁用');
        }
        
        // 更新最后登录时间
        $stmt = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
        $stmt->execute([$user['id']]);
        
        // 创建会话
        $sessionData = $this->createSession($user['id'], $rememberMe);
        
        logActivity("用户登录成功: {$user['username']}");
        sendSuccessResponse([
            'user' => [
                'id' => $user['id'],
                'username' => $user['username'],
                'email' => $user['email']
            ],
            'session' => $sessionData
        ], '登录成功');
    }
    
    private function logout() {
        $token = $this->getAuthToken();
        
        if ($token) {
            $stmt = $this->db->prepare("DELETE FROM user_sessions WHERE session_token = ?");
            $stmt->execute([$token]);
        }
        
        sendSuccessResponse(null, '退出成功');
    }
    
    private function getProfile() {
        $user = $this->requireAuth();
        
        sendSuccessResponse([
            'user' => [
                'id' => $user['id'],
                'username' => $user['username'],
                'email' => $user['email'],
                'created_at' => $user['created_at'],
                'last_login' => $user['last_login']
            ]
        ]);
    }
    
    private function verifyToken() {
        try {
            $user = $this->requireAuth();
            sendSuccessResponse(['valid' => true, 'user' => [
                'id' => $user['id'],
                'username' => $user['username'],
                'email' => $user['email']
            ]]);
        } catch (Exception $e) {
            sendSuccessResponse(['valid' => false]);
        }
    }
    
    private function updateProfile() {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        $rules = [
            'username' => [
                'min_length' => 3,
                'max_length' => 50,
                'pattern' => '/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]+$/u',
                'message' => '用户名只能包含字母、数字、下划线和中文，长度3-50个字符'
            ],
            'email' => [
                'email' => true,
                'max_length' => 100,
                'message' => '请输入有效的邮箱地址'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        $updates = [];
        $params = [];
        
        if (isset($data['username']) && $data['username'] !== $user['username']) {
            // 检查用户名是否已存在
            $stmt = $this->db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$data['username'], $user['id']]);
            if ($stmt->fetch()) {
                sendErrorResponse('用户名已存在');
            }
            $updates[] = 'username = ?';
            $params[] = $data['username'];
        }
        
        if (isset($data['email']) && $data['email'] !== $user['email']) {
            // 检查邮箱是否已存在
            $stmt = $this->db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $stmt->execute([$data['email'], $user['id']]);
            if ($stmt->fetch()) {
                sendErrorResponse('邮箱已存在');
            }
            $updates[] = 'email = ?';
            $params[] = $data['email'];
        }
        
        if (empty($updates)) {
            sendErrorResponse('没有需要更新的信息');
        }
        
        $params[] = $user['id'];
        $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        
        if ($stmt->execute($params)) {
            logActivity("用户更新资料: {$user['username']}");
            sendSuccessResponse(null, '资料更新成功');
        } else {
            sendErrorResponse('更新失败');
        }
    }
    
    private function changePassword() {
        $user = $this->requireAuth();
        $data = getRequestData();
        
        $rules = [
            'current_password' => ['required' => true, 'message' => '请输入当前密码'],
            'new_password' => [
                'required' => true,
                'min_length' => PASSWORD_MIN_LENGTH,
                'message' => '新密码长度不能少于' . PASSWORD_MIN_LENGTH . '个字符'
            ]
        ];
        
        $errors = validateInput($data, $rules);
        if (!empty($errors)) {
            sendErrorResponse('输入验证失败', 422, ['errors' => $errors]);
        }
        
        // 验证当前密码
        if (!verifyPassword($data['current_password'], $user['password_hash'])) {
            sendErrorResponse('当前密码错误');
        }
        
        // 更新密码
        $newPasswordHash = hashPassword($data['new_password']);
        $stmt = $this->db->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
        
        if ($stmt->execute([$newPasswordHash, $user['id']])) {
            // 删除所有会话，强制重新登录
            $stmt = $this->db->prepare("DELETE FROM user_sessions WHERE user_id = ?");
            $stmt->execute([$user['id']]);
            
            logActivity("用户修改密码: {$user['username']}");
            sendSuccessResponse(null, '密码修改成功，请重新登录');
        } else {
            sendErrorResponse('密码修改失败');
        }
    }
    
    private function createSession($userId, $rememberMe = false) {
        $token = generateSecureToken();
        $duration = $rememberMe ? REMEMBER_ME_DURATION : SESSION_DURATION;
        $expiresAt = date('Y-m-d H:i:s', time() + $duration);
        
        $stmt = $this->db->prepare("
            INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent) 
            VALUES (?, ?, ?, ?, ?)
        ");
        
        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
        
        $stmt->execute([$userId, $token, $expiresAt, $ipAddress, $userAgent]);
        
        return [
            'token' => $token,
            'expires_at' => $expiresAt,
            'remember_me' => $rememberMe
        ];
    }
    
    // getAuthToken() 和 requireAuth() 已在 BaseAPI 中实现
}

// 处理请求
$api = new AuthAPI();
$api->handleRequest();
?>
